package by.ins.webconsole;

import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;

import by.ins.app.commands.AppCommandConstants;

import by.ins.app.console.RemoteAdminConsole;
import by.ins.life.ILife;
import by.ins.life.evolution.ILifeEvoluter;

import by.yativem.commons.console.ConsoleCommandBean;

@RemoteProxy(name = "ins")
public class WEBRemoteConsole {
private static final Logger log = LogManager.getLogger(WEBRemoteConsole.class);
	private static Registry registry;
	private static RemoteAdminConsole server;

	protected RemoteAdminConsole getAdminConsole() {

		try {
			if (server == null) {

				registry = LocateRegistry.getRegistry("localhost", 2009);
				server = (RemoteAdminConsole) registry
						.lookup("remote-admin-console");
			}
		} catch (Exception e) {

			e.printStackTrace();
		}

		// server.register();
		return server;
	}

	@RemoteMethod
	public String callTest() {
		return "Hello;";
	}

	@RemoteMethod
	public String startIns() {
		return "Hello;";
	}

	@RemoteMethod
	public boolean isInsStarted() {
		String str = null;
		try {
			str = getAdminConsole().test();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return str != null;
	}

	@RemoteMethod
	public ILifeEvoluter[] getLifes() throws RemoteException {
		log.error("Hi eee");
		ILifeEvoluter[] result = null;
		try {
			
			 result = (ILifeEvoluter[]) getAdminConsole().sendCommand(
					new ConsoleCommandBean(
							AppCommandConstants.COMMAND_LIFEEVOLUTOR));
		} catch (Exception e) {
			log.error("", e);
		}
		return result;
	}

}
